package com.example.demo.main.rabbitmq.exchange.direct;

import com.example.demo.main.rabbitmq.utils.RabbitmqConnectionUtil;
import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

/**
 * @author xieluoyin
 */
public class Consumer4DirectExchange {

	public static void main(String[] args) throws Exception {
		
		

        Connection connection = RabbitmqConnectionUtil.getConnection();
        
        Channel channel = connection.createChannel();  
		//4 声明
		String exchangeName = "test_direct_exchange";
		String exchangeType = "direct";
		String queueName = "test_direct_queue";
		String routingKey = "test.direct";
		
		//表示声明了一个交换机
		channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
		//表示声明了一个队列
		channel.queueDeclare(queueName, false, false, false, null);
		//建立一个绑定关系:
		channel.queueBind(queueName, exchangeName, routingKey);
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String message = new String(body, StandardCharsets.UTF_8);
                System.out.println(" [Consumer] Received '" + message + "'");
            }
        };

        //参数：队列名称、是否自动ACK、Consumer
        channel.basicConsume(queueName, true, consumer);  

	}
}
